<template>
    <div class="layout-container">
        <div class="layout-container-left">
            <UseTable :tableData="tableData" unique @change="change" />
        </div>

        <div class="layout-container-right">
            <div class="form-box">
                <el-form label-width="auto">
                    <el-form-item label="平均分布">
                        <el-input v-model="evenDistribution" type="number" @change="evenDistributionChange" />
                    </el-form-item>

                    <el-form-item label="分位数数组">
                        <div class="form">
                            <div v-for="(input, index) in paramsData.quantiles" :key="index" class="input-row">
                                <el-input v-model.number="paramsData.quantiles[index]" type="number" :disabled="index !== 0" />
                                <span>-</span>
                                <el-input v-model.number="paramsData.quantiles[index+1]" type="number" placeholder="请输入参数" @input="handleInput(index)">
                                    <template #append>
                                        <el-button @click="removeInput(index+1)" :disabled="paramsData.quantiles.length <= 1" :icon="Delete" />
                                    </template>
                                </el-input>
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item>
                        <div class="data-select">
                            <DmData @dataChange="dataChange" />
                            <Upload @uploadSuccess="uploadSuccess" />
                        </div>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="handleCalculate">计算</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <el-divider />

            <div class="info-box">
                <h5>算法说明</h5>
                <p>按数据分布的分位数划分组别（如四分位数将数据分为 4 组，每组包含 25% 的数据）。</p>

                <h5>使用范围</h5>
                <ul>
                    <li>基于数据分布的均匀分组（如将收入按四分位数分为 “低收入 - 高收入”）；</li>
                    <li>消除极端值影响，反映数据的相对位置；</li>
                    <li>适用于连续型数据（如年龄、成绩）。</li>
                </ul>
            </div>
        </div>

        <Result v-model="resultShow" :originalData="paramsData" :result="resultData" />
    </div>
</template>

<script setup lang="ts">
import {onActivated, onMounted, ref} from "vue"
import {ElMessage}                   from "element-plus"
import {quantile}                    from "@/api/grouping"
import Result                        from "./components/Result.vue"
import {getExcel}                    from "@/api/data"
import {Delete}                      from "@element-plus/icons-vue"
import {isMonotonicIncreasing}       from "@/utils/arrayUtils"
import Upload                        from "@/components/Upload.vue"
import UseTable                      from "@/components/UseTable.vue"
import DmData                        from "@/components/DmData.vue"

function dataChange(data) {
    tableData.value = data
}

function uploadSuccess(res) {
    tableData.value = res.data
}

// 处理输入变化
let handleInput = (index) => {
    // 如果当前是最后一行且有值，则添加新行
    if (index === paramsData.value.quantiles.length - 1 && paramsData.value.quantiles[index] !== "") {
        paramsData.value.quantiles.push("")
    }
}

// 删除输入行
let removeInput = (index) => {
    if (paramsData.value.quantiles.length > 1) {
        paramsData.value.quantiles.splice(index, 1)
    }
}

let evenDistribution = ref(4)

function evenDistributionChange() {
    const bins = []
    const step = 1 / evenDistribution.value

    // 插入中间值
    for (let i = 1; i < evenDistribution.value; i++) {
        const value = step * i
        bins.push(Number(value.toFixed(2)))
    }

    paramsData.value.quantiles = bins
}

function change(list) {
    paramsData.value.data = list?.[0]?.value || []
}

let paramsData = ref({
    data     : [],
    quantiles: [0.25, 0.5, 0.75]
})

let resultShow = ref(false)
let resultData = ref({})

function handleCalculate() {
    if (!paramsData.value.data || paramsData.value.data.length === 0) {
        ElMessage.warning("请选择数据")
        return
    }

    if (!paramsData.value.quantiles || paramsData.value.quantiles.length === 0) {
        ElMessage.warning("请填写quantiles")
        return
    }

    let isMonotonic = isMonotonicIncreasing(paramsData.value.quantiles)
    if (!isMonotonic) {
        ElMessage.warning("区间应该单调递增")
        return
    }

    quantile(paramsData.value).then((res: any) => {
        resultData.value = res?.data
        resultShow.value = true
    })
}

let loading   = ref(true)
let tableData = ref([])

let getTableData = () => {
    loading.value = true

    getExcel("quantile").then(res => res.data).then(data => tableData.value = data)

    loading.value = false
}

/**
 * 初始化参数
 */
function initParam() {

}

// -----------------------------主程序start-----------------------------------------
onMounted(() => {
    initParam()
    getTableData()
})

onActivated(() => {
    initParam()
    getTableData()
})
// -----------------------------主程序end-----------------------------------------

</script>

<style scoped>

.input-row {
    display: flex;
    align-items: center;
    gap: 10px;
}

</style>

